<template>
  <div class="contacts-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><User /></el-icon>
          <div class="header-text">
            <h2>通讯录</h2>
            <p>企业通讯录管理</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            添加联系人
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧组织架构树 -->
      <el-col :span="6">
        <el-card shadow="never" class="org-tree-card">
          <div class="tree-header">
            <el-icon><OfficeBuilding /></el-icon>
            <span>组织架构</span>
          </div>
          <el-input
            v-model="searchTreeText"
            placeholder="搜索部门"
            clearable
            style="margin-bottom: 12px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-tree
            :data="orgTree"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            default-expand-all
            @node-click="handleDeptClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-icon><OfficeBuilding /></el-icon>
                <span>{{ node.label }}</span>
                <span class="dept-count">({{ data.count }})</span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧联系人列表 -->
      <el-col :span="18">
        <el-card shadow="never">
          <!-- 搜索栏 -->
          <div class="search-bar">
            <el-input
              v-model="searchText"
              placeholder="搜索姓名、手机号、邮箱"
              clearable
              style="width: 300px;"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-radio-group v-model="viewMode">
              <el-radio-button label="card">
                <el-icon><Grid /></el-icon>
                卡片
              </el-radio-button>
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
                列表
              </el-radio-button>
            </el-radio-group>
          </div>

          <!-- 卡片视图 -->
          <div v-if="viewMode === 'card'" class="card-view">
            <div
              v-for="contact in filteredContacts"
              :key="contact.id"
              class="contact-card"
              @click="handleViewContact(contact)"
            >
              <el-avatar :size="60" :src="contact.avatar">{{ contact.name[0] }}</el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ contact.name }}</div>
                <div class="contact-position">{{ contact.position }}</div>
                <div class="contact-dept">{{ contact.department }}</div>
              </div>
              <div class="contact-actions">
                <el-button circle @click.stop="handleCall(contact)">
                  <el-icon><Phone /></el-icon>
                </el-button>
                <el-button circle @click.stop="handleMessage(contact)">
                  <el-icon><Message /></el-icon>
                </el-button>
                <el-button circle @click.stop="handleEmail(contact)">
                  <el-icon><Message /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 列表视图 -->
          <el-table v-else :data="filteredContacts" stripe>
            <el-table-column label="姓名" width="150">
              <template #default="{ row }">
                <div class="name-cell" @click="handleViewContact(row)">
                  <el-avatar :size="36" :src="row.avatar">{{ row.name[0] }}</el-avatar>
                  <span class="name-text">{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="position" label="职位" width="150" />
            <el-table-column prop="department" label="部门" width="150" />
            <el-table-column prop="phone" label="手机号" width="130" />
            <el-table-column prop="email" label="邮箱" min-width="180" />
            <el-table-column prop="workLocation" label="办公地点" width="120" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleCall(row)">
                  <el-icon><Phone /></el-icon>
                  呼叫
                </el-button>
                <el-button link type="success" @click="handleMessage(row)">
                  <el-icon><Message /></el-icon>
                  消息
                </el-button>
                <el-button link type="warning" @click="handleEmail(row)">
                  <el-icon><Message /></el-icon>
                  邮件
                </el-button>
                <el-button link type="primary" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-if="filteredContacts.length === 0" description="暂无联系人" />

          <el-pagination
            v-if="filteredContacts.length > 0"
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[12, 24, 48]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: flex-end;"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 联系人详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="联系人详情" width="600px">
      <div v-if="currentContact" class="contact-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="currentContact.avatar">{{ currentContact.name[0] }}</el-avatar>
          <div class="header-info">
            <h3>{{ currentContact.name }}</h3>
            <p>{{ currentContact.position }} | {{ currentContact.department }}</p>
          </div>
        </div>
        <el-divider />
        <el-descriptions :column="2" border>
          <el-descriptions-item label="手机号">{{ currentContact.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentContact.email }}</el-descriptions-item>
          <el-descriptions-item label="办公电话">{{ currentContact.officePhone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="工号">{{ currentContact.employeeId }}</el-descriptions-item>
          <el-descriptions-item label="办公地点">{{ currentContact.workLocation }}</el-descriptions-item>
          <el-descriptions-item label="直属上级">{{ currentContact.supervisor || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit(currentContact)">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑联系人对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="form.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="技术部" value="技术部" />
                <el-option label="产品部" value="产品部" />
                <el-option label="市场部" value="市场部" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="办公地点" prop="workLocation">
          <el-input v-model="form.workLocation" placeholder="请输入办公地点" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User, Plus, OfficeBuilding, Search, Grid, List, Phone, Message, Edit
} from '@element-plus/icons-vue'

// 状态
const searchText = ref('')
const searchTreeText = ref('')
const viewMode = ref('card')
const currentDept = ref(null)

// 分页
const pagination = reactive({
  page: 1,
  size: 12,
  total: 24
})

// 组织架构树
const orgTree = ref([
  {
    id: 1,
    name: '公司总部',
    count: 24,
    children: [
      { id: 11, name: '技术部', count: 8 },
      { id: 12, name: '产品部', count: 6 },
      { id: 13, name: '市场部', count: 5 },
      { id: 14, name: '财务部', count: 3 },
      { id: 15, name: '人事部', count: 2 }
    ]
  }
])

// 联系人数据
const contacts = ref([
  {
    id: 1,
    name: '张三',
    position: '技术总监',
    department: '技术部',
    phone: '138****0001',
    email: 'zhangsan@company.com',
    workLocation: '北京总部',
    employeeId: 'EMP001',
    supervisor: '李总',
    avatar: ''
  },
  {
    id: 2,
    name: '李四',
    position: '高级工程师',
    department: '技术部',
    phone: '138****0002',
    email: 'lisi@company.com',
    workLocation: '北京总部',
    employeeId: 'EMP002',
    supervisor: '张三',
    officePhone: '010-88888888',
    avatar: ''
  },
  {
    id: 3,
    name: '王五',
    position: '产品经理',
    department: '产品部',
    phone: '138****0003',
    email: 'wangwu@company.com',
    workLocation: '上海分部',
    employeeId: 'EMP003',
    supervisor: '赵总',
    avatar: ''
  },
  {
    id: 4,
    name: '赵六',
    position: '市场总监',
    department: '市场部',
    phone: '138****0004',
    email: 'zhaoliu@company.com',
    workLocation: '深圳分部',
    employeeId: 'EMP004',
    supervisor: '李总',
    avatar: ''
  }
])

// 对话框
const showDialog = ref(false)
const showDetailDialog = ref(false)
const formRef = ref(null)
const currentContact = ref(null)
const dialogTitle = computed(() => currentContact.value ? '编辑联系人' : '添加联系人')

// 表单
const form = reactive({
  name: '',
  department: '',
  position: '',
  phone: '',
  email: '',
  workLocation: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
}

// 计算属性
const filteredContacts = computed(() => {
  let result = contacts.value
  if (searchText.value) {
    result = result.filter(c =>
      c.name.includes(searchText.value) ||
      c.phone.includes(searchText.value) ||
      c.email.includes(searchText.value)
    )
  }
  if (currentDept.value) {
    result = result.filter(c => c.department === currentDept.value)
  }
  return result
})

// 方法
const handleDeptClick = (data) => {
  if (data.children) {
    currentDept.value = null
  } else {
    currentDept.value = data.name
  }
}

const handleViewContact = (contact) => {
  currentContact.value = contact
  showDetailDialog.value = true
}

const handleCall = (contact) => {
  ElMessage.info(`呼叫 ${contact.name}: ${contact.phone}`)
}

const handleMessage = (contact) => {
  ElMessage.info(`发送消息给 ${contact.name}`)
}

const handleEmail = (contact) => {
  ElMessage.info(`发送邮件到 ${contact.email}`)
}

const handleEdit = (contact) => {
  currentContact.value = contact
  Object.assign(form, {
    name: contact.name,
    department: contact.department,
    position: contact.position,
    phone: contact.phone,
    email: contact.email,
    workLocation: contact.workLocation
  })
  showDetailDialog.value = false
  showDialog.value = true
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      showDialog.value = false
    }
  })
}
</script>

<style scoped>
.contacts-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.org-tree-card {
  height: calc(100vh - 220px);
  overflow-y: auto;
}

.tree-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  margin-bottom: 16px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
}

.dept-count {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  min-height: 400px;
}

.contact-card {
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.contact-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
}

.contact-info {
  text-align: center;
}

.contact-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.contact-position {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.contact-dept {
  font-size: 13px;
  color: #909399;
}

.contact-actions {
  display: flex;
  gap: 8px;
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
}

.name-cell:hover .name-text {
  color: #409EFF;
}

.contact-detail {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-info h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.header-info p {
  margin: 0;
  color: #606266;
}
</style>

